package org.adorsys.aderp.orga.service;

import java.util.List;

import org.adorsys.aderp.orga.domain.OrgaPerson;
import org.adorsys.aderp.orga.domain.OrgaResource;
import org.adorsys.aderp.orga.domain.ResourceRelation;
import org.adorsys.aderp.orga.domain.ResourceRelationRole;
import org.adorsys.aderp.orga.repository.ResourceRelationRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;


public class ResourceRelationServiceImpl implements ResourceRelationService {
	
	 @Autowired
	    ResourceRelationRepository resourceRelationRepository;
	 
	 
	public List<ResourceRelation> findByTargetResource(OrgaResource orgaResource){
		  return  resourceRelationRepository.findByTargetResource(orgaResource);
	 }
	
	
	public	List<ResourceRelation> findByPerson(OrgaPerson person){
		  return  resourceRelationRepository.findByPerson(person);

		
	}
	public	Page<ResourceRelation> findByTargetResourcePage(OrgaResource orgaResource,Integer page, Integer size){
		  return  resourceRelationRepository.findByTargetResource(orgaResource , new PageRequest(page, size));

		
		
	}
	public	Page<ResourceRelation> findByPersonPage(OrgaPerson person,Integer page, Integer size){
		  return  resourceRelationRepository.findByPerson(person, new PageRequest(page, size));

		
	}
	public Page<ResourceRelation> searchResourceRelation(OrgaPerson person, OrgaResource targetResource,
			ResourceRelationRole relationRole,Integer page, Integer size){
		
		PageRequest pageable = new PageRequest(page, size);
		
        if(person!=null && targetResource==null && relationRole==null){
        	return resourceRelationRepository.findByPerson(person, pageable);
        } else if (person!=null && targetResource!=null && relationRole==null){
        	return resourceRelationRepository.findByTargetResourceAndPerson(targetResource, person, pageable);
        } else if (person!=null && targetResource!=null && relationRole!=null){
        	return resourceRelationRepository.findByTargetResourceAndPersonAndRelationRole(targetResource, person, relationRole, pageable);
        }else if (person!=null && targetResource==null && relationRole!=null){
        	return resourceRelationRepository.findByPersonAndRelationRole(person, relationRole, pageable);
        } else if (person==null && targetResource!=null && relationRole==null){
        	return resourceRelationRepository.findByTargetResource(targetResource, pageable);
        } else if (person==null && targetResource!=null && relationRole!=null){
        	return resourceRelationRepository.findByTargetResourceAndRelationRole(targetResource, relationRole, pageable);
        } else if (person==null && targetResource==null && relationRole!=null){
        	return resourceRelationRepository.findByRelationRole(relationRole, pageable);
        } else {
        	return resourceRelationRepository.findAll(pageable);
        }
		
	}
	  
}
